package engine.graphics.popup;

import javax.microedition.lcdui.Graphics;

import engine.graphics.MapCanvasEngine;

public abstract class Popup {

	public boolean isVisible = false;

	public final void hide() {
		this.isVisible = false;
		PopupManager.hidePopup();
	}

	public final void repaint() {
		MapCanvasEngine.canvas.repaint(this.x, this.y, width, height);
	}

	public abstract void show(int screenX, int screenY);

	public abstract void keyPressed(int key);

	public int width = 135;

	public int height = 135;

	public static final int MARGIN_PANEL_HEIGHT = 17;

	protected int x;

	protected int y;

	protected final Graphics show(final int screenX, final int screenY, final Graphics graphics) {
		this.x = screenX;
		this.y = screenY;
		graphics.setColor(128, 128, 128);
		graphics.fillRect(this.x, this.y, width, height);
		this.isVisible = true;
		return graphics;
	}

	protected final int[][][] initCursor(final byte maxLines, final byte lineHeight) {
		byte lines = (byte) (110 / lineHeight);
		int[][][] vCursor;
		boolean next = (maxLines > lines && maxLines % lines != 0);
		int size = maxLines + (maxLines / lines);
		if (next)
			size++;
		vCursor = new int[size][2][2];
		int j = MARGIN_PANEL_HEIGHT;
		int i = 0;
		int k = 0;
		for (int l = 0; l < maxLines; l++) {
			vCursor[k][0][0] = 2;
			vCursor[k][0][1] = j - 1;
			vCursor[k][1][0] = 130;
			vCursor[k][1][1] = lineHeight;
			if (i == lines - 1) {
				k++;
				vCursor[k][0][0] = 113;
				vCursor[k][0][1] = 125;
				vCursor[k][1][0] = 18;
				vCursor[k][1][1] = 8;
				j = MARGIN_PANEL_HEIGHT;
				i = 0;
			} else {
				j += lineHeight;
				i++;
			}
			k++;
		}
		if (maxLines > lines && maxLines % lines != 0) {
			k = vCursor.length - 1;
			vCursor[k][0][0] = 113;
			vCursor[k][0][1] = 125;
			vCursor[k][1][0] = 18;
			vCursor[k][1][1] = 8;
		}
		return vCursor;
	}

	protected final void hideVCursor(final int[][][] vCursor, final byte vIndex) {
		Graphics graphics = MapCanvasEngine.canvas.graphics;
		graphics.setColor(192, 192, 192);
		graphics.drawRect(this.x + vCursor[vIndex][0][0], this.y + vCursor[vIndex][0][1], vCursor[vIndex][1][0],
				vCursor[vIndex][1][1]);
	}

	protected final void showVCursor(final int[][][] vCursor, final byte vIndex) {
		Graphics graphics = MapCanvasEngine.canvas.graphics;
		graphics.setColor(255, 0, 0);
		graphics.drawRect(this.x + vCursor[vIndex][0][0], this.y + vCursor[vIndex][0][1], vCursor[vIndex][1][0],
				vCursor[vIndex][1][1]);
	}

	protected final byte moveVCursor(final int[][][] vCursor, final byte vIndex, final byte dY) {
		hideVCursor(vCursor, vIndex);
		byte newVIndex = (byte) ((vIndex + dY + vCursor.length) % vCursor.length);
		showVCursor(vCursor, newVIndex);
		return newVIndex;
	}

}
